package com.baihui.taobao.transition;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Connection;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.baihui.taobao.authorize.TaoBaoSessionInfo;
import com.baihui.taobao.db.CommonDAO;
import com.baihui.taobao.db.DBConnectionMgr;
import com.baihui.taobao.db.OrderDAO;
import com.baihui.taobao.db.TPSessionDAO;
import com.baihui.taobao.db.TradeDAO;
import com.baihui.taobao.util.UnZip;
import com.baihui.taobao.util.Util;
import com.baihui.taobao.vo.BOrder;
import com.baihui.taobao.vo.BTrade;
import com.baihui.taobao.vo.BUser;
import com.taobao.api.ApiException;
import com.taobao.api.TaobaoObject;
import com.taobao.api.domain.Order;
import com.taobao.api.domain.Trade;
import com.taobao.api.internal.parser.json.ObjectJsonParser;
import com.taobao.api.request.TimeGetRequest;
import com.taobao.api.request.TopatsResultGetRequest;
import com.taobao.api.request.TopatsTradesSoldGetRequest;
import com.taobao.api.request.TradeFullinfoGetRequest;
import com.taobao.api.request.TradesSoldGetRequest;
import com.taobao.api.request.TradesSoldIncrementGetRequest;
import com.taobao.api.response.TimeGetResponse;
import com.taobao.api.response.TopatsResultGetResponse;
import com.taobao.api.response.TopatsTradesSoldGetResponse;
import com.taobao.api.response.TradeFullinfoGetResponse;
import com.taobao.api.response.TradesSoldGetResponse;
import com.taobao.api.response.TradesSoldIncrementGetResponse;

/**
 * Created by Kevin. User: HSZM1106-0312 Date: 12-1-12 Time: 下午11:00
 */
public class OrderCase extends Cases implements IViewProgressSupport {
	public static String CRMMEMEBER = "4-crmMemeber";
	public static String ORDER = "1-order";
	public static String DEALUSER = "2-dealUser";
	public static String SHIPPING = "3-shipping";

	List<String> nickList = new ArrayList<String>();

	// 创建了缓存线程池，缓存线程池的线程个数是不固定的，随着任务的增加而增加线程池中的线程数，随着任务结束而消亡
	// private static final ExecutorService threadPool = Executors
	// .newCachedThreadPool();

	public OrderCase(TaoBaoSessionInfo info) {
		super(info);
	}

	private TradesSoldGetResponse getNextPage(TradesSoldGetRequest req,
			long page, Date start, Date end) throws Exception {
		req.setPageNo(page);
		req.setStartCreated(start);
		req.setEndCreated(end);
		try {
			return getTaoBaoClient().execute(req,
					getSessionInfo().getTopSession());
		} catch (ApiException e) {
			throw new Exception(e);
		}
	}

	private TradesSoldIncrementGetResponse getNextPage(
			TradesSoldIncrementGetRequest req, long page, Date start, Date end)
			throws Exception {
		req.setPageNo(page);
		req.setStartModified(start);
		req.setEndModified(end);
		try {
			return getTaoBaoClient().execute(req,
					getSessionInfo().getTopSession());
		} catch (ApiException e) {
			throw new Exception(e);
		}
	}

	/**
	 * 同步三个月内的订单。
	 * 
	 * @throws Exception
	 */
	public void getLast3MonthSoldTrades(final TaoBaoSessionInfo sessionInfo)
			throws Exception {
		String yestoday = getYestoday("yyyyMMdd");
		String startString = getDate(-90, yestoday);
		List<Long> tids = new ArrayList<Long>();
		tids.add(uploadtids(getDate(-90, yestoday), getDate(-61, yestoday),
				sessionInfo.getTopSession()));
		tids.add(uploadtids(getDate(-60, yestoday), getDate(-31, yestoday),
				sessionInfo.getTopSession()));
		tids.add(uploadtids(getDate(-30, yestoday), yestoday,
				sessionInfo.getTopSession()));
		ArrayList<String> files = new ArrayList<String>();
		UnZip unZip = new UnZip();
		StringBuffer deleteFileBuffer = new StringBuffer();
		while (tids.size() > 0) {
			String fileName = downTids(tids.get(0));
			if (fileName != null) {
				if (!"该任务不存在".equals(fileName)) {
					unZip.unZip(fileName, "D:\\taobaodate\\");
					files.add("D:\\taobaodate\\" + tids.get(0));
				}
				deleteFileBuffer.append(tids.get(0)).append(",");
				tids.remove(0);
			}
			if (tids.size() == 0) {
				break;

			} else {
				Thread.sleep(1000 * 60 * 5);
			}
		}
		insertTrades(files);

		markImportProgress(50);
		// 导入成交买家
		exportUserToDB();
		// 根据订单的购买数据来修改对应商品的成交个数
		updateTitemIncreamnum();
		Date end = stringToDate(getYestoday("yyyy-MM-dd") + " 23:59:59");
		Date start = addDays(end, -90);
		exportShippingToDB(end, start);
		exportMemberToDB(end, start);
		// 把获取3个月内已卖出订单的结束时间做为下次增量订单同步的开始时间
		sessionInfo.setLastSyncTime(end);
		updateUserToDB(sessionInfo);

		// 删除已经处理过的文件
		deleteFile(
				"D:\\taobaodate\\",
				deleteFileBuffer.toString().substring(0,
						deleteFileBuffer.length() - 1));
	}

	public boolean deleteFile(String mypath, String files) {
		boolean isSuccess = true;
		if (files == null || "".equals(files)) {
			return true;
		}
		String[] fileList = files.split(",");
		for (int i = 0; i < fileList.length; i++) {
			try {
				File file = new File(mypath + fileList[i]);
				File fileZip = new File(mypath + fileList[i] + ".zip");
				if (file.exists()) {
					if (!file.delete()) {
						isSuccess = false;
					}
				}

				if (fileZip.exists()) {
					if (!fileZip.delete()) {
						isSuccess = false;
					}
				}

			} catch (Exception e) {
				System.out.println("Error:   " + e.getMessage());
			}

		}
		return isSuccess;
	}

	/**
	 * 后台线程定时调用：增量同步订单。
	 * 
	 * @throws Exception
	 */
	public List<Trade> getIncrementSoldTradesByPeriod(Date start, Date end)
			throws Exception {
		TradesSoldIncrementGetRequest req = new TradesSoldIncrementGetRequest();
		long page = 1;
		// req.setFields(parseFields(Trade.class));
		req.setFields("tid");
		req.setStartModified(start);
		req.setEndModified(end);
		req.setPageNo(1L);
		req.setPageSize(100L);
		req.setUseHasNext(true);
		try {
			TradesSoldIncrementGetResponse response = getTaoBaoClient()
					.execute(req, getSessionInfo().getTopSession());

			List<Trade> tradeList = new ArrayList<Trade>();
			// if (tradeList == null || tradeList.size() <= 0) {
			// return null;
			// }

			if (response.isSuccess()) {
				if(response.getTrades() != null && response.getTrades().size() > 0){
					for (Trade t : response.getTrades()) {
						Trade trade = getTradeFullInfo(t.getTid());
						if (trade != null) {
							tradeList.add(trade);
						}
					}
				}

				while (response.getHasNext()) {
					page++;
					response = getNextPage(req, page, start, end);
					if (response.isSuccess()) {
						for (Trade t : response.getTrades()) {
							Trade trade = getTradeFullInfo(t.getTid());
							if (trade != null) {
								tradeList.add(trade);
							}
						}
					} else {
						response = getNextPage(req, page, start, end);
						if (response.isSuccess()) {
							for (Trade t : response.getTrades()) {
								Trade trade = getTradeFullInfo(t.getTid());
								if (trade != null) {
									tradeList.add(trade);
								}
							}
						}
					}
				}
			} else {
				if("520".equals(response.getErrorCode())){
					getIncrementSoldTradesByPeriod(start, end);
				}
			}

			return tradeList;
		} catch (Exception e) {
			throw e;
		}
	}

	private Trade getTradeFullInfo(Long tid) throws Exception {
		TradeFullinfoGetRequest req = new TradeFullinfoGetRequest();
		req.setFields(parseFields(Trade.class));
		req.setTid(tid);
		TradeFullinfoGetResponse rsp = getTaoBaoClient().execute(req,
				getSessionInfo().getTopSession());
		if (rsp.isSuccess()) {
			return rsp.getTrade();
		} else {
			// API服务不可用或超时，则重试
			if ("520".equals(rsp.getErrorCode())) {
				return getTradeFullInfo(tid);
			} else {
				return null;
			}
		}
	}

	public String getYestoday(String dataType) {
		SimpleDateFormat format = new SimpleDateFormat(dataType);
		Date date = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(calendar.DATE, -1);
		return format.format(calendar.getTime());
	}

	public String getDate(int length, String date) {
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		Date day = null;
		try {
			day = format.parse(date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(day);
		calendar.add(calendar.DATE, length);
		return format.format(calendar.getTime());
	}

	public Date stringToDate(String dateString) {

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
				"yyyy-MM-dd hh:mm:ss");
		Date date = null;
		try {
			date = simpleDateFormat.parse(dateString);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return date;
	}

	public long uploadtids(String starttime, String endtime, String sessionkey)
			throws Exception {
		long taskId = 0L;
		try {
			TopatsTradesSoldGetRequest req = new TopatsTradesSoldGetRequest();
			req.setStartTime(starttime);
			req.setEndTime(endtime);
			req.setFields(parseFields(Trade.class));

			TopatsTradesSoldGetResponse response = getTaoBaoClient().execute(
					req, sessionkey);
			if (response.isSuccess()) {
				return response.getTask().getTaskId();
			} else {
				String subMsgString = response.getSubMsg();
				if (subMsgString.contains("TaskId=")) {
					taskId = Long.valueOf(subMsgString.substring(subMsgString
							.indexOf("TaskId=") + 7));
				} else {
					uploadtids(starttime, endtime, sessionkey);
				}
			}
		} catch (Exception e) {
			throw e;
		}
		return taskId;
	}

	public void insertTrades(ArrayList<String> files) throws Exception {
		List<Trade> tradeList = new ArrayList<Trade>();
		for (int i = 0; i < files.size(); i++) {
			// BufferedReader bf = new BufferedReader(new
			// FileReader(files.get(i)));
			InputStreamReader isr = new InputStreamReader(new FileInputStream(
					files.get(i)), "UTF-8");
			BufferedReader read = new BufferedReader(isr);

			String buff = null;
			int m = 0;
			while ((buff = read.readLine()) != null) {
				// buff = new String(buff.getBytes("utf-8"),"utf-8");
				// List<Trade> tradeList = new ArrayList<Trade>();
				ObjectJsonParser<TradeFullinfoGetResponse> parser = new ObjectJsonParser<TradeFullinfoGetResponse>(
						TradeFullinfoGetResponse.class);
				TradeFullinfoGetResponse rsp = parser.parse(buff);
				Trade trade = rsp.getTrade();
				m++;
				tradeList.add(trade);

				if (m == 100) {
					exportTradeToDB(tradeList, "3moth");
					m = 0;
					tradeList = new ArrayList<Trade>();
				}

			}
			exportTradeToDB(tradeList, "3moth");
		}
	}

	public void exportMemberToDB(Date end, Date start) {
		try {
			MemberCase memberCase = new MemberCase(this.getSessionInfo());
			memberCase.importMemberFromTaobao((long) getSessionInfo()
					.getVisitor_id(), start, end);
		} catch (Exception e) {
			log(e.getMessage());
		}
	}

	public void exportShippingToDB(Date end, Date start) {
		try {
			ShippingCase shippingCase = new ShippingCase(this.getSessionInfo());
			shippingCase.importShippingFromTaobao((long) getSessionInfo()
					.getVisitor_id(), start, end);
		} catch (Exception e) {
			log(e.getMessage());
		}
	}

	public void updateTitemIncreamnum() throws Exception {

		CommonDAO commonDAO = new CommonDAO();
		List<Map> tradeMap = commonDAO
				.findAllObject(
						"SELECT numIid,sum(num) as increamnum  FROM `tborder` where userId = ? GROUP BY numIid ",
						new Object[] { getSessionInfo().getVisitor_id() });

		// 更新商品使用.
		List<String> updateItems = new ArrayList<String>();
		for (Map map : tradeMap) {
			updateItems.add("update titem set increamnum = (increamnum + "
					+ map.get("increamnum") + "),exported = 2 where num_iid = "
					+ map.get("numIid"));
		}
		// 更新批量商量数据
		commonDAO.updateAndInsert(updateItems, null);
		markImportProgress(58);
	}

	public void exportUserToDB() throws Exception {

		// 获取交易相关的用户的昵称
		CommonDAO commonDAO = new CommonDAO();
		List<String> nickList = (List<String>) commonDAO.findListString(
				"Select DISTINCT(buyerNick) from tbtrade where userId = ? ",
				new Object[] { getSessionInfo().getVisitor_id() });
		UserCase userCase = new UserCase(getSessionInfo());
		userCase.exportUserToDB(BUser.DEAL, (long) getSessionInfo()
				.getVisitor_id(), nickList);

		nickList.clear();
	}

	public void exportUserToDBIncream() throws Exception {

		// 获取交易相关的用户的昵称
		// CommonDAO commonDAO = new CommonDAO();
		// List<String> nickList = (List<String>) commonDAO.findListString(
		// "Select DISTINCT(buyerNick) from tbtrade where userId = ? ",
		// new Object[] { getSessionInfo().getVisitor_id() });
		UserCase userCase = new UserCase(getSessionInfo());
		userCase.exportUserToDB(BUser.DEAL, (long) getSessionInfo()
				.getVisitor_id(), nickList);

		nickList.clear();
	}

	// private void getSoldTradesByPeriod(Date start, Date end) throws Exception
	// {
	// TradesSoldGetRequest req = new TradesSoldGetRequest();
	// long page = 1;
	// req.setFields(parseFields(Trade.class));
	// req.setStartCreated(start);
	// req.setEndCreated(end);
	// req.setPageNo(1L);
	// req.setPageSize(100L);
	// req.setUseHasNext(true);
	// try {
	// TradesSoldGetResponse response = getTaoBaoClient().execute(req,
	// getSessionInfo().getTopSession());
	// List<Trade> tradeList = new ArrayList<Trade>();
	// if (response.isSuccess()) {
	// tradeList = response.getTrades();
	// if (tradeList == null || tradeList.size() <= 0)
	// return;
	// exportTradeToDB(tradeList, "3moth");
	// while (response != null && response.getHasNext() != null) {
	// // 存在第二页
	// Util.stopOneMinute();
	// page++;
	// response = getNextPage(req, page, start, end);
	// if (response.isSuccess()) {
	// exportTradeToDB(response.getTrades(), "3moth");
	// } else {
	// response = getNextPage(req, page, start, end);
	// exportTradeToDB(response.getTrades(), "3moth");
	// }
	// }
	//
	// } else {
	// System.out.println("重新链接date ===" + start + "~~~~~" + end);
	// getSoldTradesByPeriod(start, end);
	// }
	//
	// } catch (Exception e) {
	// throw e;
	// }
	// }

	public void IncrementSoldTrades(final TaoBaoSessionInfo sessionInfo)
			throws Exception {

		Date end = getTaobaoTime();
		Date start = sessionInfo.getLastSyncTime();
		long result = end.getTime() - start.getTime();
		if (result >= (24 * 60 * 60 * 1000)) {

			Calendar calendar = Calendar.getInstance();
			calendar.setTime(start);
			calendar.add(Calendar.SECOND, (24 * 60 * 60 - 1));
			end = calendar.getTime();

		}
		markImportProgress(5);
		try {
			// 取增量订单信息
			List<Trade> tradeList = getIncrementSoldTradesByPeriod(start, end);
			markImportProgress(10);
			if(tradeList != null && tradeList.size() < 1){
				sessionInfo.setLastSyncTime(end);
				updateUserToDB(sessionInfo);
				return;
			}
			// 第二个参数标识 3moth：三个月数据 increment：增量数据
			exportTradeToDB(tradeList, "increment");
			exportUserToDBIncream();
			sessionInfo.setLastSyncTime(end);
			updateUserToDB(sessionInfo);

			exportShippingToDB(end, start);
			Long endLong3 = System.currentTimeMillis();
			// logger.info("获取三个月的物流信息用时 " + (endLong3 - endLong2) + "毫秒");
			exportMemberToDB(end, start);
			markImportProgress(70);
		} catch (ApiException e) {
			logger.error("同步" + sessionInfo.getVisitor_id() + "的增量订单失败："
					+ start + "-" + end, e);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static void main(String[] a) throws ParseException {
		// Date date = new Date();
		// System.out.println("date" + date);
		// Calendar calendar = Calendar.getInstance();
		// calendar.setTime(date);
		// calendar.add(Calendar.SECOND, (24 * 60 * 60 - 1));
		// System.out.println("date11" + calendar.getTime());
		// String adateStrteStr = null;
		// SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
		// "yyyy-MM-dd hh:mm:ss");
		// Date date = simpleDateFormat.parse(adateStrteStr);
		// System.out.println("date11" + date);
		String dateString = "2010-02-02" + " 23:59:59";
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
				"yyyy-MM-dd hh:mm:ss");
		Date date = null;
		try {
			date = simpleDateFormat.parse(dateString);
			System.out.println("date = " + date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private Date addHours(Date date, int amount) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(Calendar.HOUR_OF_DAY, amount);
		return c.getTime();
	}

	private void updateUserToDB(TaoBaoSessionInfo user) throws Exception {
		TPSessionDAO userDAO = new TPSessionDAO();
		userDAO.updateAndInsert(
				"update topsession set lastSyncTime = ?  where user_id = ?",
				new Object[] { user.getLastSyncTime(), user.getVisitor_id() });
	}

	/**
	 * 获取淘宝服务器时间作为当前时间，避免部分ISV机器时间提前时导致同步漏单现象。
	 */
	public Date getTaobaoTime() {
		TimeGetRequest req = new TimeGetRequest();
		try {
			TimeGetResponse rsp = getTaoBaoClient().execute(req);
			if (rsp.isSuccess()) {
				return rsp.getTime();
			}
		} catch (ApiException e) {
		}
		return new Date();
	}

	/**
	 * 导订单信息到中间库
	 * 
	 */
	private void exportTradeToDB(List<Trade> tradeList, String dateType)
			throws Exception {

		Connection cn = null;
		try {
			if (tradeList != null && tradeList.size() > 0) {
				// 保存交易中的订单
				List<BOrder> allInsertOrders = new ArrayList<BOrder>(); // 存放修改过后的BOrder
				List<BTrade> allInsertTrades = new ArrayList<BTrade>(); // 存放修改过后的BTrade
				List<BTrade> allUpdateTrades = new ArrayList<BTrade>(); // 存放修改过后的BTrade
				List<BOrder> allUpdateOrders = new ArrayList<BOrder>(); // 存放修改过后的BTrade

				// 由于存在购物车的形式，不同卖家可能对应的tid相同。
				List<String> tidList = getTradeByUser();
				List<String> oidList = getOrderByUser();
				// 循环拼装数据
				for (Trade trade : tradeList) {

					// 转换成我们的Info对象BTrade
					BTrade bTrade = new BTrade();
					// 拷贝源对象中的值到目标对象
					Util.copy(bTrade, trade);
					// 如果在数据库中存在,更新
					if (tidList != null
							&& tidList.contains(String.valueOf(trade.getTid()))) {
						bTrade.setUserId((long) getSessionInfo()
								.getVisitor_id());
						if ("3moth".equals(dateType)) {
							continue;
						} else {
							allUpdateTrades.add(bTrade);
						}
					} else {
						// 设置当前的用户ID
						bTrade.setUserId((long) getSessionInfo()
								.getVisitor_id());
						bTrade.setExported(0);
						allInsertTrades.add(bTrade);
					}
					if (!nickList.contains(bTrade.getBuyerNick())) {
						nickList.add(bTrade.getBuyerNick());
					}

					// 拼装交易中的订单，一次交易可能存在多个订单.
					if (trade.getOrders() != null
							&& trade.getOrders().size() > 0) {
						for (Order order : trade.getOrders()) {

							// 转换成我们的Info对象BOrder
							BOrder bOrder = new BOrder();
							// 拷贝源对象中的值到目标对象
							Util.copy(bOrder, order);
							// 如果在数据库中存在，则更新.
							if (oidList != null
									&& oidList.contains(String.valueOf(order
											.getOid()))) {
//								bOrder.setParent(trade);
//								bOrder.setBuyerNick(trade.getBuyerNick());
								bOrder.setUserId((long) getSessionInfo()
										.getVisitor_id());
//								bOrder.setExported(2);
								allUpdateOrders.add(bOrder);
							} else {
								// 设置当前用户ID和订单所属的父亲交易
								bOrder.setParent(trade);
								bOrder.setBuyerNick(trade.getBuyerNick());
								bOrder.setUserId((long) getSessionInfo()
										.getVisitor_id());
								bOrder.setExported(0);
								allInsertOrders.add(bOrder);
							}
						}
					}
				}
				markImportProgress(30);
				cn = DBConnectionMgr.getConnection();
				// cn.setAutoCommit(false);

				markImportProgress(35);
				// 插入交易到数据库中.
				// log("更新交易表");
				TradeDAO tradeDAO = new TradeDAO();
				if (allInsertTrades != null && allInsertTrades.size() > 0) {
					tradeDAO.insertTrade(allInsertTrades, cn);
				}
				if (allUpdateTrades != null && allUpdateTrades.size() > 0) {
					// TODO: 由于之前只有一个tid是主键，现在又多了一个userid，更新会操作userid，有问题，所在暂时注释
					// 2010.06.26
					 tradeDAO.updateTrade(allUpdateTrades, cn);
				}
				markImportProgress(40);
				// 插入到订单表中
				// log("更新订单表");
				OrderDAO orderDAO = new OrderDAO();
				if (allInsertOrders != null && allInsertOrders.size() > 0) {
					orderDAO.insertOrder(allInsertOrders, cn);
				}
				if (allUpdateOrders != null && allUpdateOrders.size() > 0) {
					 orderDAO.updateOrder(allUpdateOrders, cn);
				}
				markImportProgress(47);

			} else {
				cn = DBConnectionMgr.getConnection();
				// cn.setAutoCommit(false);
			}

			// cn.commit();
		} catch (Exception e) {
			throw e;
		} finally {
			if (cn != null)
				cn.close();
		}
	}

	public void markImportProgress(int progress) {
		// System.out.println("当前进度：" + progress + "%");
		getSessionInfo().setOrderImportProgress(progress);
	}

	public int viewImportProgress() {
		return getSessionInfo().getOrderImportProgress();
	}

	/**
	 * 获取批次插入的参数
	 * 
	 * @param module
	 * @param startDate
	 * @param endDate
	 * @param lotNo
	 * @return
	 */
	private Object[] getParams(String module, Timestamp startDate,
			Timestamp endDate, int lotNo) {
		Object[] params = new Object[7];
		params[0] = getSessionInfo().getVisitor_id();
		params[1] = new Integer(0);
		params[2] = module;
		params[3] = startDate;
		params[4] = new Integer(lotNo);
		params[5] = startDate;
		params[6] = endDate;
		return params;
	}

	public String downTids(Long taskid) throws MalformedURLException,
			IOException, ApiException {

		// HttpServletRequest req = ServletActionContext.getRequest();
		// String pathString = req.getServletPath();
		String url = "";
		TopatsResultGetRequest req1 = new TopatsResultGetRequest();
		req1.setTaskId(taskid);
		TopatsResultGetResponse response1 = getTaoBaoClient().execute(req1);
		if (response1.isSuccess()) {
			url = response1.getTask().getDownloadUrl();
		} else {
			return response1.getSubMsg();
		}
		if (url == null || url.equals(""))
			return null;
		System.out.println(getSessionInfo().getVisitor_id() + ":开始下载,任务号："
				+ taskid + new Date());
		int buffer = 2048;
		byte data[] = new byte[buffer];
		int count = -1;
		InputStream in = new URL(url).openStream();
		String fileName = "D://taobaodate/" + taskid + ".zip";
		OutputStream oStream = new FileOutputStream(fileName);

		while ((count = in.read(data, 0, buffer)) != -1) {
			oStream.write(data, 0, count);
		}
		System.out.println(getSessionInfo().getVisitor_id() + "结束下载，任务号："
				+ taskid + new Date());

		return fileName;
	}

	/**
	 * 本用户对应的交易信息
	 * 
	 * @return
	 */
	public List<String> getTradeByUser() throws Exception {
		CommonDAO commonDAO = new CommonDAO();
		List<String> tradeMap = commonDAO.findListString(
				"select tid from tbtrade where userId = ? ",
				new Object[] { getSessionInfo().getVisitor_id() });
		return tradeMap;
	}

	/**
	 * 本用户对应的订单信息
	 * 
	 * @return
	 */
	public List<String> getOrderByUser() throws Exception {
		CommonDAO commonDAO = new CommonDAO();
		List<String> tradeMap = commonDAO.findListString(
				"select oid from tborder where userId = ? ",
				new Object[] { getSessionInfo().getVisitor_id() });
		return tradeMap;
	}

	public Date addDays(Date date, int amount) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(Calendar.DATE, amount);
		return c.getTime();
	}
}
